import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, InputNumber, Cascader, Select } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import {
  add,
  edit,
  update,
  getTypeList,
  getLabelList,
} from '@/services/blogAdmin/article/article/api';
import CUpload from '@/components/common/CUpload/index';
import CBraftEditor from '@/components/common/CBraftEditor';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(porps.id ? false : true);
  const [typeList, setTypeList] = useState<any>([]);
  const [typeListLoading, setTypeListLoading] = useState<boolean>(false);
  const [labelArrList, setLabelArrList] = useState<any>([]);
  const [labelArrListLoading, setLabelArrListLoading] = useState<boolean>(false);
  const [typeArr, settypeArr] = useState<any>([]);

  const { TextArea } = Input;
  const formData: API.BlogAdminArticleForm = {
    id: null,
    name: '',
    status: 1,
    sort: 1,
    article_type_id: null,
    download_url: '',
    download_key: '',
    image_id: null,
    keywords: '',
    description: '',
    content: '',
    labelArr: [],
  };
  return (
    <DrawerForm<API.AdminProjectForm>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await settypeArr(res.data.type_arr);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        if (!Number.isInteger(values.image_id)) {
          values.image_id = values.image_id && values.image_id[0].id;
        }
        if (!values.image_id) {
          values.image_id = null;
        }
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await settypeArr(res.data.type_arr);
              await setLoading(true);
            }
          }
          await setTypeListLoading(true);
          const typeRes = await getTypeList();
          if (typeRes.status == 20000) {
            await setTypeListLoading(false);
            await setTypeList(typeRes.data);
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Spin spinning={typeListLoading}>
              <Form.Item
                label="文章类型"
                name="article_type_id"
                rules={[{ required: true, message: '请选择文章类型' }]}
              >
                {typeListLoading === false && (
                  <>
                    <Cascader
                      options={typeList}
                      defaultValue={typeArr}
                      allowClear
                      placeholder="请选择文章类型"
                      onChange={async (value) => {
                        if (value.length) {
                          await restFormRef.current?.setFieldsValue({
                            article_type_id: value[value.length - 1],
                          });
                        } else {
                          await restFormRef.current?.setFieldsValue({ article_type_id: null });
                        }
                      }}
                      fieldNames={{ value: 'id', label: 'name' }}
                    />
                  </>
                )}
              </Form.Item>
            </Spin>

            <Form.Item
              label="文章名称"
              name="name"
              rules={[{ required: true, message: '请输入文章名称' }]}
            >
              <Input maxLength={100} allowClear placeholder="请输入文章名称" />
            </Form.Item>
            <Form.Item label="下载地址" name="download_url">
              <Input maxLength={100} allowClear placeholder="请输入下载地址" />
            </Form.Item>
            <Form.Item label="下载秘钥" name="download_key">
              <Input maxLength={100} allowClear placeholder="请输入下载秘钥" />
            </Form.Item>
            <Form.Item name="image_id" label="图片">
              <CUpload
                key="image_id"
                imageList={
                  restFormRef.current?.getFieldValue('image_to')
                    ? [restFormRef.current.getFieldValue('image_to')]
                    : []
                }
                onChange={(data: any) => {
                  if (!data.length) {
                    restFormRef.current?.setFieldsValue({ image_id: null });
                  }
                }}
              />
            </Form.Item>

            <Form.Item label="文章详情" name="content">
              <CBraftEditor
                value={formData.content}
                onChange={async (value: string) => {
                  await restFormRef.current?.setFieldsValue({ content: value });
                }}
              />
            </Form.Item>
            <Form.Item label="文章关键词" name="keywords">
              <TextArea showCount maxLength={250} placeholder="请输入文章关键词" />
            </Form.Item>
            <Form.Item label="文章描述" name="description">
              <TextArea showCount maxLength={250} placeholder="请输入文章描述" />
            </Form.Item>
            <Form.Item label="文章标签" name="labelArr">
              <Select
                allowClear
                mode="tags"
                style={{ width: '100%' }}
                placeholder="请选择文章标签"
                maxTagCount={10}
                loading={labelArrListLoading}
                // onChange={(value) => {
                //   console.log(value);
                // }}
                onSearch={async (value) => {
                  await setLabelArrList([]);
                  await setLabelArrListLoading(true);
                  const res = await getLabelList({ name: value });
                  if (res.status === 20000) {
                    const arr = [];
                    for (let i = 0; i < res.data.length; i++) {
                      arr.push({ value: res.data[i] });
                    }
                    await setLabelArrList(arr);
                    await setLabelArrListLoading(false);
                  }
                }}
                options={labelArrList}
              />
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group name="status">
                <Radio value={0}>禁用</Radio>
                <Radio value={1}>启用</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序' }]}>
              <InputNumber
                maxLength={11}
                placeholder="请输入排序"
                min={0}
                decimalSeparator="0"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
